﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //tableView显示属性设置
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setAlternatingRowColors(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openTable()
{
    //打开数据表
    m_tableModel = new QSqlTableModel(this, m_db);   //数据表
    m_tableModel->setTable("employee");  //设置数据表
    m_tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);   //手动提交
    m_tableModel->setSort(m_tableModel->fieldIndex("empNo"),
                         Qt::SortOrder::AscendingOrder);    //升序排列
    if (!(m_tableModel->select())) { //查询数据
        QMessageBox::critical(this, "错误", "打开数据表失败，错误信息\n" +
                              m_tableModel->lastError().text(),
                              QMessageBox::Ok, QMessageBox::NoButton);
        return ;
    }
    //这是显示子段
    //字段显示名
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("empNo"),Qt::Horizontal,"工号");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Name"),Qt::Horizontal,"姓名");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Gender"),Qt::Horizontal,"性别");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Height"),Qt::Horizontal,"身高");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Birthday"),Qt::Horizontal,"出生日期");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Mobile"),Qt::Horizontal,"手机");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Province"),Qt::Horizontal,"省份");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("City"),Qt::Horizontal,"城市");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Department"),Qt::Horizontal,"部门");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Education"),Qt::Horizontal,"学历");
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Salary"),Qt::Horizontal,"工资");

    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Memo"),Qt::Horizontal,"备注"); //这两个字段不再tableView中显示
    m_tableModel->setHeaderData(m_tableModel->fieldIndex("Photo"),Qt::Horizontal,"照片");

    //设置选择模型
    m_theSelection = new QItemSelectionModel(m_tableModel);  //选择模型
    connect(m_theSelection, &QItemSelectionModel::currentChanged,
            this, &MainWindow::currentChanged);
    connect(m_theSelection, &QItemSelectionModel::currentRowChanged,
            this, &MainWindow::currentRowChanged);

    //设置显示
    ui->tableView->setModel(m_tableModel);
    ui->tableView->setSelectionModel(m_theSelection);
    ui->tableView->setColumnHidden(m_tableModel->fieldIndex("Memo"), true);
    ui->tableView->setColumnHidden(m_tableModel->fieldIndex("Photo"), true);
    //tableView上为“性别”和“部门”两个字段设置自定义代理组件
    QStringList strList;
    strList<<"男"<<"女";
    bool isEditable=false;
    m_delegateSex.setItems(strList,isEditable);
    ui->tableView->setItemDelegateForColumn(
       m_tableModel->fieldIndex("Gender"), &m_delegateSex); //Combbox选择型

    strList.clear();
    strList<<"销售部"<<"技术部"<<"生产部"<<"行政部";
    isEditable=true;
    m_delegateDepart.setItems(strList,isEditable);
    ui->tableView->setItemDelegateForColumn(m_tableModel->fieldIndex("Department"),&m_delegateDepart); //Combbox选择型

//创建界面组件与数据模型的字段之间的数据映射
    m_dataMapper= new QDataWidgetMapper();
    m_dataMapper->setModel(m_tableModel);//设置数据模型
    m_dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);//

//界面组件与tabModel的具体字段之间的联系
    m_dataMapper->addMapping(ui->dbSpinEmpNo,m_tableModel->fieldIndex("empNo"));
    m_dataMapper->addMapping(ui->dbEditName,m_tableModel->fieldIndex("Name"));
    m_dataMapper->addMapping(ui->dbComboSex,m_tableModel->fieldIndex("Gender"));
    m_dataMapper->addMapping(ui->dbSpinHeight,m_tableModel->fieldIndex("Height"));
    m_dataMapper->addMapping(ui->dbEditBirth,m_tableModel->fieldIndex("Birthday"));
    m_dataMapper->addMapping(ui->dbEditMobile,m_tableModel->fieldIndex("Mobile"));
    m_dataMapper->addMapping(ui->dbComboProvince,m_tableModel->fieldIndex("Province"));
    m_dataMapper->addMapping(ui->dbEditCity,m_tableModel->fieldIndex("City"));
    m_dataMapper->addMapping(ui->dbComboDep,m_tableModel->fieldIndex("Department"));
    m_dataMapper->addMapping(ui->dbComboEdu,m_tableModel->fieldIndex("Education"));
    m_dataMapper->addMapping(ui->dbSpinSalary,m_tableModel->fieldIndex("Salary"));
    m_dataMapper->addMapping(ui->dbEditMemo,m_tableModel->fieldIndex("Memo"));

    m_dataMapper->toFirst();//移动到首记录

    getFieldNames();//获取字段名称列表，填充ui->groupBoxSort组件

//更新actions和界面组件的使能状态
    ui->actOpenDB->setEnabled(false);

    ui->actRecAppend->setEnabled(true);
    ui->actRecInsert->setEnabled(true);
    ui->actRecDelete->setEnabled(true);
    ui->actScan->setEnabled(true);

    ui->groupBoxSort->setEnabled(true);
    ui->groupBoxFilter->setEnabled(true);

}

void MainWindow::getFieldNames()
{
    QSqlRecord record = m_tableModel->record(); //获取空记录(只获取字段)
    for (int i = 0; i < record.count(); i++) {
        ui->comboFields->addItem(record.fieldName(i));
    }
}

void MainWindow::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(current);
    Q_UNUSED(previous);
    ui->actSubmit->setEnabled(m_tableModel->isDirty());
    ui->actRevert->setEnabled(m_tableModel->isDirty());
}

void MainWindow::currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);
    //菜单栏状态更改
    ui->actRecDelete->setEnabled(current.isValid());
    ui->actPhoto->setEnabled(current.isValid());
    ui->actPhotoClear->setEnabled(current.isValid());
    if (!current.isValid()) {
        ui->dbLabPhoto->clear();
        return ;
    }
    m_dataMapper->setCurrentIndex(current.row());  //更新数据映射的行号
    int curRecNo = current.row();
    QSqlRecord curRec = m_tableModel->record(curRecNo);  //获取当前行号的记录
    if (curRec.isNull("Photo")) {
        ui->dbLabPhoto->clear();
    }
    else {
        QByteArray data = curRec.value("Photo").toByteArray();
        QPixmap pic;
        pic.loadFromData(data);
        ui->dbLabPhoto->setPixmap(pic.scaledToWidth(ui->dbLabPhoto->size().width()));
    }
}


void MainWindow::on_actOpenDB_triggered()
{
    //打开数据库
    QString aFile = QFileDialog::getOpenFileName(this,
                                                 "选择数据库文件","../",
                                                 "SQLite数据库(*.db *.db3");
    if (aFile.isEmpty())
        return ;
    m_db = QSqlDatabase::addDatabase("QSQLITE"); //添加SQLite数据库
    m_db.setDatabaseName(aFile);
    if (!m_db.open()) {  //打开数据库
        QMessageBox::warning(this, "错误", "打开数据库失败",
                             QMessageBox::Ok, QMessageBox::NoButton);
        return ;
    }
    openTable();    //打开数据表
}

void MainWindow::on_actRecAppend_triggered()
{
    m_tableModel->insertRow(m_tableModel->rowCount());
    QModelIndex curIndex = m_tableModel->index(m_tableModel->rowCount() - 1, 1);
    m_theSelection->clearSelection();
    m_theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select); //选择指定的

    int curRow = curIndex.row();    //获取当前行号
    m_tableModel->setData(m_tableModel->index(curRow, 0), 2000 + m_tableModel->rowCount());
    m_tableModel->setData(m_tableModel->index(curRow, 2), "男");
}

void MainWindow::on_actRecInsert_triggered()
{
    QModelIndex curIndex = ui->tableView->currentIndex();   //获取当前选中行
    m_tableModel->insertRow(curIndex.row());
    m_theSelection->clearSelection();
    m_theSelection->setCurrentIndex(m_tableModel->index(curIndex.row(), 1),
                                    QItemSelectionModel::Select);
}

void MainWindow::on_actRecDelete_triggered()
{
    QModelIndex curIndex = ui->tableView->currentIndex();
    m_tableModel->removeRow(curIndex.row());
}

void MainWindow::on_actSubmit_triggered()
{
    bool result = m_tableModel->submitAll();    //保存
    if (!result) {
        QMessageBox::information(this, "消息", "数据保存错误，错误信息\n" +
                                 m_tableModel->lastError().text(),
                                 QMessageBox::Ok, QMessageBox::NoButton);
    }
    else {
        ui->actSubmit->setEnabled(false);
        ui->actRevert->setEnabled(false);
    }
}

void MainWindow::on_actRevert_triggered()
{
    m_tableModel->revertAll();  //取消保存
    ui->actSubmit->setEnabled(false);
    ui->actRevert->setEnabled(false);
}

void MainWindow::on_radioBtnAscend_clicked()
{
    //升序
    m_tableModel->setSort(ui->comboFields->currentIndex(), Qt::AscendingOrder);
    m_tableModel->select();
}

void MainWindow::on_radioBtnDescend_clicked()
{
    //降序
    m_tableModel->setSort(ui->comboFields->currentIndex(), Qt::DescendingOrder);
    m_tableModel->select();
}

void MainWindow::on_radioBtnMan_clicked()
{
    m_tableModel->setFilter("Gender='男'");
}

void MainWindow::on_radioBtnWoman_clicked()
{
    m_tableModel->setFilter("Gender='女'");
}

void MainWindow::on_radioBtnBoth_clicked()
{
    m_tableModel->setFilter("");
}
